package org.third.security.crypto;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SymmetricEncryption {
    static final Logger logger = LoggerFactory.getLogger(SymmetricEncryption.class);
    public static final String plainText = "(plain Text )";

    public static final String password = "pass-word";

    /**
     * 将二进制转换成16进制
     * 
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        // return org.jasypt.commons.CommonUtils.toHexadecimal(buf);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     * 
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {

        // return org.jasypt.commons.CommonUtils.fromHexadecimal(hexStr);
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static final byte[] encryptAsAES(String content, String password) {
        try {
            javax.crypto.KeyGenerator kgen = javax.crypto.KeyGenerator.getInstance(CryptoAlgorithm.AES.getName());
            kgen.init(CryptoAlgorithm.AES.getKeySize(), new java.security.SecureRandom(password.getBytes()));
            javax.crypto.SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            javax.crypto.spec.SecretKeySpec key = new SecretKeySpec(enCodeFormat, CryptoAlgorithm.AES.getName());
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CryptoAlgorithm.AES.getName());// 创建密码器
            // Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            // //密钥必须是16位的;待加密内容的长度必须是16的倍数

            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final byte[] decryptAsAES(byte[] content, String password) {
        try {
            javax.crypto.KeyGenerator kgen = javax.crypto.KeyGenerator.getInstance(CryptoAlgorithm.AES.getName());
            kgen.init(CryptoAlgorithm.AES.getKeySize(), new java.security.SecureRandom(password.getBytes()));
            javax.crypto.SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            javax.crypto.spec.SecretKeySpec key = new SecretKeySpec(enCodeFormat, CryptoAlgorithm.AES.getName());
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CryptoAlgorithm.AES.getName());// 创建密码器
            cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void testAES() throws Exception {
        logger.info("testAES");
        String content = "test";
        String password = "12345678";
        // 加密
        System.out.println("加密前：" + content);
        byte[] encryptResult = encryptAsAES(content, password);//
        String encryptResultStr = parseByte2HexStr(encryptResult);
        System.out.println("加密后：" + encryptResultStr);

        // 解密
        // byte[] encryptResult = parseHexStr2Byte(encryptResultStr);
        byte[] decryptResult = decryptAsAES(encryptResult, password);
        System.out.println("解密后：" + new String(decryptResult));
    }

    @Test
    public void testPBEWithMD5AndDES() throws Exception {
        logger.info("testPBEWithMD5AndDES");
        String content = "test";
        String password = "12345678";
        // 加密
        System.out.println("加密前：" + content);
        byte[] encryptResult = encryptAsPBEWithMD5AndDES(content, password);//
        String encryptResultStr = parseByte2HexStr(encryptResult);
        System.out.println("加密后：" + encryptResultStr);

        // 解密
        // byte[] encryptResult = parseHexStr2Byte(encryptResultStr);
        byte[] decryptResult = decryptAsPBEWithMD5AndDES(encryptResult, password);
        System.out.println("解密后：" + new String(decryptResult));
    }

    public static final  byte[] encryptAsPBEWithMD5AndDES(String content, String password) throws Exception {
        // 使用PBEWithMD5AndDES算法获取Cipher实例
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        
        // 基于密码生成 初始化密钥（secret key）
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        KeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        
        // 初始化Cipher为加密器
        byte [] salt = new byte[]{1,2,3,4,5,6,7,8};
//        RandomSaltGenerator saltGenerator = new RandomSaltGenerator();
        int iterationCount=1000;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

        // 对数据进行加密
        byte[] encryptedData = cipher.doFinal(content.getBytes());

        // 输出加密后的内容
        return encryptedData;

    }

    public static final  byte[] decryptAsPBEWithMD5AndDES(byte[] content, String password) throws Exception {

        // 使用PBEWithMD5AndDES算法获取Cipher实例
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        // 初始化密钥
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        KeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        // 初始化Cipher为解密器
        byte [] salt = new byte[]{1,2,3,4,5,6,7,8};
        int iterationCount=1000;
        PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec);

        // 获得解密后的数据
        byte[] decryptedData = cipher.doFinal(content);

        return decryptedData;
    }
}
